package com.ocm.tourism.core.dao.jpa;

import java.util.List;

import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.ocm.tourism.core.dao.ParticipantDao;
import com.ocm.tourism.core.domain.Participant;
import com.ocm.tourism.core.model.FieldCriteria;
import com.ocm.tourism.core.model.SearchCriteria;
import com.ocm.tourism.core.search.build.SQLBuilder;

@Repository("participantDao")
public class JpaParticipantDao extends JpaGenericDao<Participant> implements ParticipantDao {

   SQLBuilder sqlBuilder;

   @Autowired
   public JpaParticipantDao(@Qualifier("participantSQLBuilder")SQLBuilder sqlBuilder) {
      this.setClazz(Participant.class);
      this.sqlBuilder = sqlBuilder;
   }

   @SuppressWarnings("unchecked")
   public List<Participant> findAll(int firstResult, int maxResults) {
      Query query = this.entityManager().createQuery("SELECT b FROM Participant b", Participant.class).setFirstResult(firstResult).setMaxResults(maxResults);
      List<Participant> participants = query.getResultList();
      return participants;
   }

   @Override
   public Long count() {
      Query query = this.entityManager().createQuery("SELECT COUNT(b) FROM Participant b", Long.class);
      long count = (Long) query.getSingleResult();
      return count;
   }

   public boolean hasParticipant(String username) {
      Query query = this.entityManager().createQuery("SELECT count(b) FROM Participant b WHERE lower(b.username)=:username", Long.class);
      query.setParameter("username", username.toLowerCase());
      long count = (Long) query.getSingleResult();
      if (count > 0)
         return true;
      return false;
   }

   @SuppressWarnings("unchecked")
   @Override
   public Participant findByUserName(String username) {
      Query query = this.entityManager().createQuery("SELECT b FROM Participant b WHERE lower(b.username)=:username", Participant.class);
      query.setParameter("username", username.toLowerCase());
      List<Participant> participants = query.getResultList();
      if (participants.size() > 0)
         return participants.get(0);
      return null;
   }

   @SuppressWarnings("unchecked")
   @Override
   public List<Participant> findParticipants(SearchCriteria searchCriteria, int firstResult, int maxResults) {
      Query query = this.entityManager().createQuery(sqlBuilder.buildSQL(searchCriteria), Participant.class).setFirstResult(firstResult).setMaxResults(maxResults);
      List<FieldCriteria> criterias = searchCriteria.getFieldCriterias();
      for (FieldCriteria criteria : criterias){
         query.setParameter(criteria.getName(), criteria.getValue());
      }
      List<Participant> participants = query.getResultList();
      return participants;
   }
}
